import uuid, os, requests, json, re, time, datetime, random, hashlib, xml
from django.db.models import F, Q
from rest_framework import serializers, status, generics, mixins, viewsets
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework.response import Response
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from functools import reduce
from urllib.parse import unquote_plus
from decimal import Decimal
from django.conf import settings
from django.core.cache import cache
from base.models import *
from base.serializers import *
from base.tasks import add, mul, xsum
from celery.result import AsyncResult
from rest_framework.pagination import PageNumberPagination


class Pagination(PageNumberPagination):
    # 定pagination类
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = 'page'
    max_page_size = 100

    # def get_my_next(self):
    #     return settings.SERVER_NAME + self.request.path + self.get_next_link().split(self.request.path)[1]
    
    # def get_my_pre(self):
    #     return settings.SERVER_NAME + self.request.path + self.get_previous_link().split(self.request.path)[1]

    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'data': data
        })


class TestView(APIView):
    def get(self, request):
        '''
        测试接口
        '''
        try:
            json_data = {"message": "ok", "errorCode": 0, "data": {}}
            is_open = request.GET.get('is_open')
            print('*' * 128)
            # time.sleep(1)
            if is_open == 'mytestkey':
                json_data['message'] = '开始了测试'
                # 测试cache
                # timeout=0 立即过期 timeout=None 永不超时
                cache.set("key", "value", timeout=None)
                print(cache.get('key'))
            return Response(json_data)
        except Exception as e:
            print('发生错误：',e)
            return Response({"message": "出现了无法预料的view视图错误：%s" % e, "errorCode": 1, "data": {}})


class BeginCelery(APIView):
    def get(self, request):
        '''
        测试开启celery
        '''
        try:
            json_data = {"message": "ok", "errorCode": 0, "data": {}}
            print('开始测试celery...')
            if request.GET.get('task_type') == '0':
                res = mul.delay(3, 5)
                # 指定队列运行
                # res = mul.apply_async((3, 5), queue='add')
                json_data['msg'] = 'mul run...'
            elif request.GET.get('task_type') == '1':
                res = add.delay(3, 5)
                # 指定队列运行
                # res = add.apply_async((6, 9), queue="add")
                json_data['msg'] = 'add run...'
            elif request.GET.get('task_type') == '2':
                res = xsum.delay([3, 5, 7, 9])
                json_data['msg'] = 'xsum run...'
            else:
                res = mul.delay(3, 5)
                json_data['msg'] = 'mul run...'
            # say.delay()
            # 返回的是key
            # print(mul_result)
            # res=AsyncResult(mul_result).result  # 参数为task_id
            # print(dir(mul_result))
            # print(mul_result.result)
            json_data['data']['task_d'] = str(res)
            return Response(json_data)
        except Exception as e:
            print('发生错误：',e)
            return Response({"message": "出现了无法预料的view视图错误：%s" % e, "errorCode": 1, "data": {}})


from django_celery_results.models import TaskResult


class TaskResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = TaskResult
        fields = '__all__'
# 异步任务视图
class TaskResultViewset(ModelViewSet):
    '''
    修改局部数据
    create:  创建系统字典
    retrieve:  检索某个系统字典
    update:  更新系统字典
    destroy:  删除系统字典
    list:  获取系统字典列表
    '''
    queryset = TaskResult.objects.all()
    # authentication_classes = (JWTAuthentication,)
    # permission_classes = [BaseAuthPermission, ]
    # throttle_classes = [VisitThrottle]
    serializer_class = TaskResultSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('task_id', )
    filter_fields = ('status', )
    # ordering_fields = ('update_time', 'create_time',)
    pagination_class = Pagination